package com.yrxy.thread.interview.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
 * @author huanglaoxie(微信:yfct-8888)
 * @className ReentrantReadWriteLockDemo
 * @description：
 * @date 2017/6/29 15:07
 */
public class ReentrantReadWriteLockDemo {
    private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
    private static String message = "a";
    public static void main(String[] args) throws InterruptedException{
        Thread t1 = new Thread(new Read());
        Thread t2 = new Thread(new WriteB());
        Thread t3 = new Thread(new WriteC());
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
    }
    static class Read implements Runnable {
        public void run() {
            for(int i = 0; i<= 10; i ++) {
                if(lock.isWriteLocked()) {
                    System.out.println("I'll take the lock from Write");
                }
                lock.readLock().lock();
                System.out.println("ReadThread " + Thread.currentThread().getId() + " ---> Message is " + message );
                lock.readLock().unlock();
            }
        }
    }
    static class WriteB implements Runnable {
        public void run() {
            for(int i = 0; i<= 10; i ++) {
                try {
                    lock.writeLock().lock();
                    message = message.concat("b");
                    System.out.println("WriteThread " + Thread.currentThread().getId() + " ---> Message is " + message );
                } finally {
                    lock.writeLock().unlock();
                }
            }
        }
    }

    static class WriteC implements Runnable {
        public void run() {
            for(int i = 0; i<= 10; i ++) {
                try {
                    lock.writeLock().lock();
                    message = message.concat("c");
                    System.out.println("WriteThread " + Thread.currentThread().getId() + " ---> Message is " + message );
                } finally {
                    lock.writeLock().unlock();
                }
            }
        }
    }

}
